//
//  CalendarViewController.swift
//  YLH
//
//  Created by qinjiangtao on 2024/1/11.
//

import UIKit
import BRPickerView

class CalendarViewController: UIViewController {
    
    private var dateBtn = UIButton()
    private let calendarTool = QITools()
    private var showDate = Date()
    private var dateStr = ""
    private var dataArr = [CalendarModelListModel]()
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.navigationBar.isHidden = true
        getData()
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        navigationController?.navigationBar.isHidden = false
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        dateStr = calendarTool.theTargetDateConversionStr(showDate, dateFormat: "yyyy-MM")
        
        addUI()
    }
    
    private func getData() {
        dataArr.removeAll()
        QINetworkManager.requestJson(urlStr: "/Calendar/index", method: .get, parameters: ["date": dateStr]) { json in
            print(json)
            self.dataArr = json.arrayObject?.kj.modelArray(CalendarModelListModel.self) ?? [CalendarModelListModel]()
            self.collectionView.reloadData()
            self.collectionView.mj_header?.endRefreshing()
        }
    }
    
    private func addUI() {
        self.view.addGradientColor(fromColors: [ColorWithStr("#FFD1D6").cgColor, ColorWithStr("#FFFFFF").cgColor, ColorWithStr("#F6F7F9").cgColor], locationArr: [0, 0.5, 1.0], with: .topToBottom)
        
        dateBtn = UIButton().then {
            $0.frame = CGRect(x: 100, y: STATUSBAR_HEIGHT, width: SCREEN_WIDTH - 200, height: 44)
            $0.titleLabel?.font = SYSFONTBOLD(ofSize: 14)
            $0.setTitle(dateStr, for: .normal)
            $0.setTitleColor(Color333333, for: .normal)
            $0.setImage(UIImage(named: "红箭头下"), for: .normal)
            $0.addTarget(self, action: #selector(dateBtnClick), for: .touchUpInside)
        }
        view.addSubview(dateBtn)
        dateBtn.setButtonImagePosition(.right, spacing: 5)
        
        let dateTitleView = UIView()
        dateTitleView.frame = CGRect(x: 10, y: NAV_HEIGHT + 10, width: SCREEN_WIDTH - 20, height: 34)
        dateTitleView.backgroundColor = ColorWithStr("#FFF1E3")
        dateTitleView.addRoundedCorners(withRadius: 17)
        view.addSubview(dateTitleView)
        
        let dateStrArr = ["日", "一", "二", "三", "四", "五", "六"]
        let labelW = (SCREEN_WIDTH - 20) / 7
        for (index, str) in dateStrArr.enumerated() {
            let dateStrL = UILabel().then({
                $0.frame = CGRect(x: labelW * CGFloat(index), y: 0, width: labelW, height: 34)
                $0.text = str
                $0.textColor = Color333333
                $0.textAlignment = .center
                $0.font = SYSFONT(ofSize: 12)
            })
            dateTitleView.addSubview(dateStrL)
        }
        
        collectionView.frame = CGRect(x: 0, y: dateTitleView.bottom + 10, width: SCREEN_WIDTH, height: 700)
        view.addSubview(collectionView)
        
        let addBtn = UIButton().then {
            $0.frame = CGRect(x: SCREEN_WIDTH - 41, y: SCREEN_HEIGHT - TABBAR_HEIGHT - 60, width: 36, height: 36)
            $0.setImage(UIImage(named: "添加日历"), for: .normal)
            $0.addTarget(self, action: #selector(addBtnClick), for: .touchUpInside)
        }
        view.addSubview(addBtn)
        
        let todayBtn = UIButton().then {
            $0.frame = CGRect(x: addBtn.left - 51, y: SCREEN_HEIGHT - TABBAR_HEIGHT - 60, width: 36, height: 36)
            $0.setImage(UIImage(named: "今天"), for: .normal)
            $0.addTarget(self, action: #selector(todayBtnClick), for: .touchUpInside)
        }
        view.addSubview(todayBtn)
        
    }
    
    
    @objc private func dateBtnClick() {
        let dateView = BRDatePickerView()
        dateView.pickerMode = .YM
        dateView.title = "月份"
        dateView.resultBlock = {selectDate, selectValue in
            print(selectValue ?? "")
            self.dateBtn.setTitle(selectValue!, for: .normal)
            self.dateStr = selectValue ?? ""
            self.showDate = self.calendarTool.theTargetStringConversionDate(selectValue!, dateFormat: "yyyy-MM")
            self.getData()
//            self.collectionView.reloadData()
        }
        dateView.show()
    }
    
    @objc private func addBtnClick() {
        let ctl = NewSchedulerViewController()
        navigationController?.pushViewController(ctl, animated: true)
    }
    
    @objc private func todayBtnClick() {
        showDate = Date()
        dateStr = calendarTool.theTargetDateConversionStr(showDate, dateFormat: "yyyy-MM")
        dateBtn.setTitle(dateStr, for: .normal)
        self.getData()
    }
    
    lazy var collectionView: UICollectionView = {
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.minimumLineSpacing = 1
        flowLayout.minimumInteritemSpacing = 1
        flowLayout.sectionInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
        
        let collectionView = UICollectionView(frame: CGRect(x: 0, y: 100, width: SCREEN_WIDTH, height: 700), collectionViewLayout: flowLayout)
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.backgroundColor = .clear
        collectionView.register(UICollectionReusableView.classForCoder(), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "headerView")
        collectionView.mj_header = MJRefreshHeader(refreshingBlock: {
            self.getData()
        })
        return collectionView
    }()
  

}

extension CalendarViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout{
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let cellW = (SCREEN_WIDTH - 30) / 7
        return CGSize(width: cellW, height: 100)
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let amonthOf1_Date = calendarTool.getAMonthframDate(showDate, months: 0)
        return calendarTool.getNextNMonth(forDays: showDate) + calendarTool.getFirstDayWeek(forMonth: amonthOf1_Date)
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        collectionView.register(CalendarViewCell.classForCoder(), forCellWithReuseIdentifier: "CalendarViewCell\(indexPath.row)")
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CalendarViewCell\(indexPath.row)", for: indexPath) as! CalendarViewCell
        cell.backgroundColor = ColorEEEEEE
        let amonthOf1_Date = calendarTool.getAMonthframDate(showDate, months: 0)
        if indexPath.item < calendarTool.getFirstDayWeek(forMonth: amonthOf1_Date) {
            cell.model = CalendarModelListModel()
        } else {
//            var calenderStr = ""
            var number = 0
            number = calendarTool.getFirstDayWeek(forMonth: amonthOf1_Date)
//            calenderStr = "\(indexPath.item - number + 1)"
            if dataArr.count > indexPath.item - number {
                var model = dataArr[indexPath.item - number]
                model.allDate = "\(dateStr)-\(model.date)"
                cell.model = model
            }
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        var number = 0
        let amonthOf1_Date = calendarTool.getAMonthframDate(showDate, months: 0)
        number = calendarTool.getFirstDayWeek(forMonth: amonthOf1_Date)
        let index = indexPath.item - number
        guard index >= 0 else {
            return
        }
        
        let preview = CalendarPreviewView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT))
//        preview.addMatterBlock = {
//            self.addBtnClick()
//        }
        QINPopUpTool.sharedInstance().popUp(with: preview, withToViewCtl: self, withAnimation: .none, withCanTapBgCancel: true, closeBefore: .node)
        
        if dataArr.count > index && index >= 0 {
            var model = dataArr[index]
            model.allDate = "\(dateStr)-\(model.date)"
            preview.model = model
        }
    }
    
}



class CalendarViewCell: UICollectionViewCell {
    
    private var dayL = UILabel()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = .white
        self.addRoundedCorners(withRadius: 5)
        addUI()
    }
    
    private func addUI() {
        
        dayL = UILabel().then({
            $0.frame = CGRect(x: 10, y: 0, width: 30, height: 25)
            $0.tag = 11
            $0.text = ""
            $0.textColor = Color333333
            $0.font = SYSFONT(ofSize: 12)
        })
//        self.addSubview(dayL)
        
    }
    
    var model = CalendarModelListModel() {
        didSet {
            if model.list.count > 0 {
                // 删除之前的标签
                for childView in self.subviews {
                    if childView.tag != 11 {
                        childView.removeFromSuperview()
                    }
                }
                
                self.backgroundColor = ColorWithStr("#FFEFEF")
                let cellW = (SCREEN_WIDTH - 30) / 7 - 6
                for (index, childModel) in model.list.enumerated() {
                    let titleL = UILabel().then({
                        $0.frame = CGRect(x: 3, y: 25 + index * 15, width: Int(cellW), height: 13)
                        $0.backgroundColor = UIColor.rgbConversionColorl(rgbStr: childModel.color)
                        $0.text = childModel.class_name
                        $0.textAlignment = .center
                        $0.textColor = .white
                        $0.font = SYSFONT(ofSize: 10)
                        $0.addRoundedCorners(withRadius: 4)
                    })
                    self.addSubview(titleL)
                }
            } else {
                self.backgroundColor = ColorEEEEEE
                self.removeAllSubviews()
            }
            
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "yyyy-MM-dd" // 设置日期格式
            let currentDate = dateFormatter.string(from: Date())
            if model.allDate == currentDate {
                self.addBorder(withWidth: 1, borderColor: MainColor)
            } else {
                self.addBorder(withWidth: 0, borderColor: .white)
            }
            dayL.text = model.date
            self.addSubview(dayL)
        }
    }
    
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
